package cn.tedu.csmall.passport.config;

import cn.tedu.csmall.passport.security.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * JWT = JSON Web Token
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){

        //告诉Security 的加密机制
        return new BCryptPasswordEncoder();
    }

    //实现认证,当认证成功后,生成JWT并返回
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //放行的配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //禁用防跨域攻击
        http.csrf().disable();
        //URL白名单
        String[] urls = {
                "/admins/login",
                "/doc.html",
                //两个**表示路径是若干层级的
                //根据控制台F12 的Console 和 Network(网络) 查出来下面对应的路径 一定得学会自找
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/favicon.ico"

        };
        //配置各请求路径的认证和授权
        http.authorizeRequests()  //请求需要授权才可以访问
           .antMatchers(urls) //匹配一些路径
          .permitAll()  //允许直接访问(不需要经过认证和授权)
         .anyRequest() //匹配除了以上配置的其他请求
        .authenticated();// 都需要认证

        //注册处理JWT的过滤器
        //此过滤器必须在Spring Security处理登录的过滤器之前
        //request --->Filter过滤器 --->DispatcherServlet --->Interceptor拦截器 --->Controller控制器
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        //完成后,重启项目,无论对那个路径发出请求,在控制台都可以看到输出了过滤器的输出语句且在浏览器中显示一片空白
        //过滤器的特点就是 "只要找的是我的服务器,就归我管!"


    }
}
